package com.pkk.penguin.frame.know.boot.utils;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.util.FileUtil;

/**
 * @description: 执行工具类
 * @author: peikunkun
 * @create: 2020-02-28 16:11
 **/
public class ExecUtil {

  //读取json文件
  public static JSONObject readJsonFile(String fileName) {
    String jsonStr = "";
    jsonStr = readFileToString(fileName);
    if (jsonStr == null) {
      return null;
    }
    if (StringUtils.isBlank(jsonStr)) {
      return null;
    }
    return JSONObject.parseArray(jsonStr).getJSONObject(0);
  }


  /**
   * 读取配置文件
   *
   * @param fileName
   * @return
   */
  public static String readExeSQLFromTxt(String fileName) {
    return readFileToString(fileName);
  }

  /**
   * @Description: 清除上次执行结果, 以防止下次继续执行
   * @Param: fileName
   * @Param time
   * @Param result
   * @return: void
   * @Author: peikunkun
   * @Date: 2020/3/3 0003 上午 10:16
   */
  public static void cleanExeSQL(String fileName, Long time, JSONArray result) {
    final File file = new File(fileName);
    FileUtil.deleteContents(file);
    FileUtil.writeAsString(file, "\n┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓\n"
        + "┃\n"
        + "┃ 耗时:" + time + "ms\n"
        + "┃ 结果:" + result + "\n"
        + "┃\n"
        + "┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛\n");
  }


  /**
   * @Description: 读取配置文件转为String
   * @Param: fileName
   * @return: java.lang.String
   * @Author: peikunkun
   * @Date: 2020/3/2 0002 下午 1:17
   */
  public static String readFileToString(String fileName) {
    String jsonStr;
    try {
      File jsonFile = new File(fileName);
      FileReader fileReader = new FileReader(jsonFile);
      Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
      int ch = 0;
      StringBuffer sb = new StringBuffer();
      while ((ch = reader.read()) != -1) {
        sb.append((char) ch);
      }
      fileReader.close();
      reader.close();
      jsonStr = sb.toString();
    } catch (IOException e) {
      e.printStackTrace();
      return null;
    }
    return jsonStr;
  }
}
